/*
 * Copyright (C) 2010 Tetsuya Yasuda <tetsuyayasuda@gmail.com>
 */
package jp.tyas.libs.lisp;

import java.util.List;
import java.util.ListIterator;

public class UserFunc extends Callee
{
    List dargs, dbody;
    Context lex;

    public UserFunc (String name, List dargs, List dbody, boolean asFunc, Context lex)
    {
        super (name, asFunc);
        this.dargs = dargs;
        this.dbody = dbody;
        this.lex = lex;
    }

    public UserFunc (String name, List dargs, List dbody, Context lex)
    {
        this (name, dargs, dbody, true, lex);
    }

    public Object call (List args, Context ctx)
    {
        ctx = new SymbolContext (lex);

        int i, size = dargs.size ();
        for (i = 0; i < size; i++)
            ctx.set (new Symbol (((Symbol)dargs.get(i)).getName (), args.get(i), null));

        ctx.set (new Symbol ("$REST", args.subList (i, args.size()), null));
        ctx.set (new Symbol ("$ENV", ctx, null));

        Object res = null;
        ListIterator it = dbody.listIterator ();
        while (it.hasNext())
            res = Builtin.eval (it.next(), ctx);

        return res;
    }
}
